﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

#region user added usings 
// user added
using System.Text;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Linq;
#endregion

namespace SmartHYU_TestVersion.News
{
    /*************************************************
     * 
     *       Class for Download and Store HY News
     *      
     * 
     ***************************************************/

    public class HyNews
    {
        /*******************************
         *      Properties
         *******************************/
        //private string rssUrlForHyNews = "http://www.hynews.ac.kr/rss/S1N8.xml";
        // private string rssUrlForHyNews = "http://icewall.hanyang.ac.kr/hyum/hynews.php";
        private string rssUrlForHyNews = "http://www.hanyang.ac.kr/user/boardList.action?command=rss_list&siteId=hanyangkr2&boardId=223&boardType=02";
        private const string rssFileName = "hyNews.rss";
        private string rssXML;

        public string TextForDebug;
        public List<HyNewsForm> HyNewsList = new List<HyNewsForm>();
        

        /*******************************
         *      Public Methods
         *******************************/

        public bool DownloadNewsAndStore() {
            WebClient newsDownloader = new WebClient();
            
            // Downlaod News RSS files
            newsDownloader.DownloadStringAsync(new Uri(rssUrlForHyNews) );
            newsDownloader.DownloadStringCompleted +=new DownloadStringCompletedEventHandler(newsDownloader_DownloadStringCompleted);

            return true;
        }

        // Load file(/hyNews.rss) from isolated storage and parse
        //      save results to this.HyNewsList
        //      returns true when success
        public bool LoadAndParseToHyNewsForm()
        {
            IsolatedStorageFile newsStorage = IsolatedStorageFile.GetUserStoreForApplication();
            
            // If file doesn't exist, download file and save first
            if (!newsStorage.FileExists(rssFileName)) 
            {
                MessageBox.Show("RSS file doesn't exist");
                return false;
            }

            this.rssXML = loadRssFromNewsStorage(newsStorage);

            // Parsing with LINQ
            XDocument newsParser = XDocument.Parse(this.rssXML);

            var newsLinqResult = from newsLinq in newsParser.Descendants("item")
                                 select new HyNewsForm 
                                {
                                    Title = newsLinq.Element("title").Value,
                                    Url = newsLinq.Element("link").Value,
                                    Description = newsLinq.Element("description").Value,
                                    Author = newsLinq.Element("author").Value
                                    //PubDate = newsLinq.Element("pubDate").Value
                                };
            // END : Parsing with LINQ

            // ------------------------------------

            // Extract LINQ Results to News List
            foreach (var newsElements in newsLinqResult)
            {
                HyNewsForm hyNews = new HyNewsForm();

                hyNews.Title = newsElements.Title;
                hyNews.Url = newsElements.Url;
                hyNews.Description = newsElements.Description.Replace("&nbsp;","");
                hyNews.Author = newsElements.Author;
                hyNews.PubDate = newsElements.PubDate;

                this.HyNewsList.Add(hyNews);
            }
            // END : Extract LINQ Results to News List
            

            return true;
        }

        /*******************************
         *      Private Methods
         *******************************/

        // Called by DownloadNewsAndStore when download is completed
        //      store RSS file to Isolated storage using storeRSS()
        //      and generates event : NewsDownloadCompleted
        private void newsDownloader_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            // check connection - if not, do nothing 
            if (e.Error != null)
            {
                onNewsDownloadCompleted();
                return;
            }

            this.rssXML = e.Result;

            // store RSS to local storage
            this.storeRss();

            // Generate Event
            onNewsDownloadCompleted();
        }


        // Stores RSS XML strings in isolated storage : /hyNews.rss
        //      called by DownloadNewsAndStore() -> newsDownloader_DownloadStringComplted(...)
        //      returns true when success
        //      returns false when error/exception occurs ( + MessageBox warning )
        protected bool storeRss() 
        {
            using( IsolatedStorageFile newsStorage = IsolatedStorageFile.GetUserStoreForApplication() ) {
                IsolatedStorageFileStream newsStorageStream = 
                    new IsolatedStorageFileStream(rssFileName, FileMode.Create, newsStorage);
                StreamWriter newsWriter = new StreamWriter(newsStorageStream);

                // writing process
                try 
                {
                    newsWriter.Write(this.rssXML);
                } 

                //exception handling
                catch (Exception ex) 
                {
                    MessageBox.Show("Exception has occured while writing news XML : "+ ex.Message.ToString() );
                    return false;
                }

                // close streams
                newsWriter.Close();
                newsStorageStream.Close();
            }
            
            return true;
        }

        // Read RSS XML file (/hyNews.rss) and 
        //      returns RSS string
        protected string loadRssFromNewsStorage(IsolatedStorageFile newsRssStorage) 
        {
            string newsXml;
            IsolatedStorageFileStream newsFileStream = 
                new IsolatedStorageFileStream(rssFileName, FileMode.Open, newsRssStorage);
            StreamReader newsReader = new StreamReader(newsFileStream);

            try
            {
                newsXml = newsReader.ReadToEnd();
            }
            catch (Exception ex) 
            {
                MessageBox.Show("Exception occured while reading News File:" + ex.Message);
                newsXml = null;
            }

            newsReader.Close();
            newsFileStream.Close();

            return newsXml;
        }

        /*******************************
         *      User Defined Events
         *******************************/
        // Generates event when download is completed with RSS
        public delegate void NewsDownloadStatus(bool completedStatus, string rssString);
        public event NewsDownloadStatus NewsDownloadCompleted;
        protected void onNewsDownloadCompleted() { NewsDownloadCompleted(true, this.rssXML); }
    }

    public class HyNewsForm 
    {
        public string Title     { get; set; }
        public string Url       { get; set; }
        public string Description { get; set; }
        public string Author    { get; set; }
        public string PubDate   { get; set; }
    }
}
